package com.leave.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.leave.entity.User;
import com.leave.service.IUserService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class UserController {
	
	@Autowired
	private IUserService userService;
	
	
	
	@RequestMapping(value="/userAuth",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String userAuth(Model model,User user,String roleName) {
		Subject currentUser = SecurityUtils.getSubject();  
		JSONObject js = new JSONObject();
		if (currentUser.isAuthenticated()) {
			js.put("url", "/index");
			return js.toString();
		}
		//token安全令牌
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserLoginname(), user.getUserPassword()); 
		try {  
		 	//调用登录,会自动进入realm
            currentUser.login(token);
            if(currentUser.hasRole(roleName)) {
            	Session session=currentUser.getSession();
            	session.setAttribute("subject", currentUser);
            	session.setAttribute("roleName", roleName);
            	//登陆成功
            	js.put("url", "/index");
    			return js.toString();
            }else {
            	currentUser.logout();
            	js.put("errorInfo", "请确认角色是否正确!");
            	js.put("url", "/login");
    			return js.toString();
            }
            //登陆失败.抛出异常
        } catch (AuthenticationException e) {  
            js.put("errorInfo", "账号或密码错误!");
        	js.put("url", "/login");
			return js.toString();
       }  
	}
	
	@RequestMapping("/getAllUserByPage")
	@ResponseBody
	public String getAllUserByPage(Integer page,Integer rows) {
		HashMap<String,Object> map = userService.getAllUserByPage(page, rows);
		List<User> userList = (List<User>) map.get("userList");
		JSONArray jsArr = JSONArray.fromObject(userList);
		JSONObject js = new JSONObject();
		js.put("total", map.get("total"));
		js.put("rows", jsArr);
		return js.toString();
	}
	
	@RequestMapping(value="/getUserByLoginName",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getUserByLoginName(String loginName) {
		User u = userService.getUserByLoginName(loginName);
		JSONObject js = new JSONObject();
		js.put("user", u);
		return js.toString();
	}
	
	@RequestMapping("/removeUserByArrUserId")
	@ResponseBody
	public String removeUserByArrUserId(int[] arrId) {
		int i = userService.removeUserByArrId(arrId);
		if(i == arrId.length) {
			return "success";
		}
		return "false";
	}
	
	@RequestMapping("/addUser")
	@ResponseBody
	public String addUser(User u ) {
		User user = userService.getUserByLoginName(u.getUserLoginname());
		if(user !=null) {
			return "exist";
		}
		int i = userService.addUser(u);
		if(i > 0) {
			return "success";
		}
		return "false";
	}
	
	@RequestMapping("/updateUserByUser")
	@ResponseBody
	public String updateUserByUser(User u ) {
		User user = userService.getUserByLoginName(u.getUserLoginname());
		if(user !=null && !user.getUserLoginname().equals(u.getUserLoginname())) {
			return "exist";
		}
		int i = userService.updateUserByUser( u );
		if(i > 0) {
			return "success";
		}
		return "false";
	}
	
	@RequestMapping("/getUserAndRoleByPage")
	@ResponseBody
	public String getUserAndRoleByPage(Integer page,Integer rows) {
		HashMap<String,Object> map = userService.getAllUserAndHasRoleByPage(page, rows);
		List<User> userList = (List<User>) map.get("userList");
		JSONArray jsArr = JSONArray.fromObject(userList);
		JSONObject js = new JSONObject();
		js.put("total", map.get("total"));
		js.put("rows", jsArr);
		return js.toString();
	}
	@RequestMapping("/editRoleOfUser")
	@ResponseBody
	public String editRoleOfUser(int[] roleId,int userId) {
		userService.deleteRoleOfUser(userId);
		userService.addRoleOfUser(userId, roleId);
		return "success";
	}
	
	
}
